package controller

import (
	"context"
	"github.com/gin-gonic/gin"
	"github.com/go-playground/validator/v10"
	enTranslations "github.com/go-playground/validator/v10/translations/en"
	jaTranslations "github.com/go-playground/validator/v10/translations/ja"
	zhTranslations "github.com/go-playground/validator/v10/translations/zh"
	"net/http"
	"saleforce/sf-backend-gateway/i18n"
	"saleforce/sf-backend-gateway/validate"
	user_service "saleforce/sf-backend-user/service"
	pr "saleforce/sf-common/params/backend-user"
	bu "saleforce/sf-common/protoc/backend-user"
	resp "saleforce/sf-common/response"
	utl "saleforce/sf-common/utils"
)

type LoginController struct{}

func (l LoginController) Logout(c *gin.Context) {
	c.GetHeader("")
}
func (l LoginController) Login(c *gin.Context) {
	var param pr.LoginParam
	lang := c.GetHeader("lang")
	trans, _ := validate.Uni.GetTranslator(lang)
	switch lang {
	case "cn":
		_ = zhTranslations.RegisterDefaultTranslations(validate.Validate, trans)
	case "jp":
		_ = jaTranslations.RegisterDefaultTranslations(validate.Validate, trans)
	case "en":
		_ = enTranslations.RegisterDefaultTranslations(validate.Validate, trans)
	default:
		_ = zhTranslations.RegisterDefaultTranslations(validate.Validate, trans)
	}
	if err := c.ShouldBind(&param); err != nil {
		if errs, ok := err.(validator.ValidationErrors); ok {
			c.JSON(http.StatusOK, resp.Resp{}.Warning(501, errs[0].Translate(trans)))
			return
		}
		c.JSON(http.StatusOK, resp.Resp{}.Warning(502, i18n.T(err.Error(), lang)))
		return
	}
	var lg = new(bu.LoginParam)
	lg.Username = param.Username
	lg.Password = param.Password
	lg.Lang = lang
	lg.Ip = utl.GetClientIP(c)
	cb := context.Background()
	login, err := user_service.LoginService{}.Login(cb, lg)
	if err != nil {
		c.JSON(http.StatusOK, resp.Resp{}.Warning(503, i18n.T(err.Error(), lang)))
		return
	}
	var a any = login
	c.JSON(http.StatusOK, resp.Resp{}.Success(&a))
	return
}
